import dayjs from "dayjs";
import { getAppointmentShopDateTimeTable } from "@src/api/reservation";
import {
  RE_DATE_STATE,
  RE_DATE_STATE_TEXT,
} from "@src/common/reservation/constant/index.js";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import payBehavior from "@src/sp-reservation/pages/submit_reservation/payBehavior";
import base from "@src/store/base";
const DAY_TEXT = {
  0: "周日",
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
};
const resolveTime = (time) => {
  const timeIndex = time.indexOf(":");
  const mm = Number(time.slice(timeIndex + 1, time.length));
  const hh = Number(time.slice(0, timeIndex));
  if (mm < 30) {
    return `${hh < 10 ? "0" + hh : hh}:00`;
  } else if (mm > 30) {
    return `${hh + 1 < 10 ? "0" + hh + 1 : hh + 1}:00`;
  } else {
    return time;
  }
};

const resolveDifferHour = (bt, et) => {
  const btIndex = bt.indexOf(":");
  const etIndex = et.indexOf(":");
  const bthh = Number(bt.slice(0, btIndex));
  const ethh = Number(et.slice(0, etIndex));
  return ethh - bthh;
};

Component({
  behaviors: [storeBindingsBehavior, payBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms", "businessName"],
    },
  ],
  properties: {
    reservationScope: {
      type: Number,
      value: 0,
    },
    selectCategoryId: {
      type: [Number, String],
      value: "",
    },
    appointmentCategoryId: {
      type: Number,
      value: 0,
    },
    selectPlanId: {
      type: Number,
      value: 0,
    },
    shopInfo: {
      type: Object,
      value: () => {},
    },
  },
  data: {
    //日期段
    date: "", //选择的日期
    dateIndex: 0,
    dateOptions: [],
    //每个时间段
    timeOptions: [],
    timeIndex: 0,
    RE_DATE_STATE,
    RE_DATE_STATE_TEXT,
    loading: true,
  },
  observers: {},
  pageLifetimes: {
    show: function () {
      // 页面被展示
      console.log("页面被展示");
      this.getDateTime();
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    },
  },
  ready() {
    this.setData({
      date: dayjs().add(0, "day").format("MM-DD"),
    });
    this.getDateTime();
  },
  methods: {
    //开关弹窗
    handleClose() {
      this.triggerEvent("close");
    },
    handleSelectReservationTime() {
      const { timeOptions, timeIndex, dateOptions, dateIndex } = this.data;
      this.triggerEvent("select", {
        time: timeOptions[timeIndex],
        date: dateOptions[dateIndex],
      });
    },
    //获取日期
    getDateTime() {
      wx.showLoading({ title: "加载排期中" });
      this.setData({
        loading: true,
      });
      let list = [];
      for (let i = 0; i < this.data.reservationScope; i++) {
        const dateMD = dayjs().add(i, "day").format("MM-DD");
        const dateYMD = dayjs().add(i, "day").format("YYYY-MM-DD");
        const day = DAY_TEXT[dayjs().add(i, "day").get("day")];
        let text = "";
        if (i === 0) {
          text = "今天" + dateMD;
        } else if (i === 1) {
          text = "明天" + dateMD;
        } else if (i === 2) {
          text = "后天" + dateMD;
        } else {
          text = day + dateMD;
        }
        list.push({
          label: text,
          value: dateYMD,
        });
      }
      this.setData({
        dateOptions: list,
      });
      //获取选择的时间段
      this.fetchData().then(() => {
        wx.hideLoading();
        this.setData({
          loading: false,
        });
        this.handleSelectReservationTime();
      });
    },

    //日期选择
    async handleSelectDate(e) {
      // if (
      //   this.data.selectCategoryId === null ||
      //   this.data.selectCategoryId === undefined
      // ) {
      //   wx.showModal({
      //     title: "提示",
      //     content: "请先选择资源/项目",
      //     showCancel: false,
      //     success: (res) => {
      //       if (res.confirm) {
      //         this.triggerEvent("close");
      //         this.triggerEvent("showSelectGood");
      //       }
      //     },
      //   });
      //   return;
      // }
      const {
        currentTarget: {
          dataset: { modelvalue },
        },
      } = e;
      this.setData({
        dateIndex: modelvalue,
      });
      await this.fetchData();
      this.handleSelectReservationTime();
    },
    async fetchData() {
      const { code, data } = await getAppointmentShopDateTimeTable({
        appointmentCategoryId:
          this.data.appointmentCategoryId > 0
            ? this.data.appointmentCategoryId
            : "",
        levelId:
          this.data.selectCategoryId !== null &&
          this.data.selectCategoryId !== undefined
            ? this.data.selectCategoryId
            : "",
        planId: this.data.selectPlanId,
        date: this.data.dateOptions[this.data.dateIndex].value,
        shopId: this.data.shopInfo.shopInfoResp.shopId,
      });
      if (code === 0) {
        const alowed = data.findIndex((v) => v.status === 1);
        this.setData({
          timeOptions: data,
          timeIndex: alowed,
        });
      }
    },
    handleSelectTime(e) {
      const {
        currentTarget: {
          dataset: { modelvalue },
        },
      } = e;
      if (this.data.timeOptions[modelvalue].status !== 1) {
        return;
      }
      this.setData({
        timeIndex: modelvalue,
      });
      this.handleSelectReservationTime();
    },
  },
});
